package top.xiaoyu.dao.impl;

import top.xiaoyu.entity.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * JDBC Demo
 * 下载MySQL驱动并导入，maven的话直接引入依赖即可
 * 在代码中将驱动包进行加载
 * 将驱动包交给驱动管理器，由驱动管理器获取数据库连接
 * 由数据库连接获取数据库操作对象
 * 如果sql语句是查询语句，需要处理返回结果集
 * sql中有?进行替换
 * 执行sql
 * 关闭connection和statement
 */
public class MainTest04 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/test";
        String user = "root";
        String password = "Dong1314520.";
        Connection connection = DriverManager.getConnection(url, user, password);
        PreparedStatement preparedStatement = connection.prepareStatement("select * from t_user");
        // 返回结果集
        ResultSet resultSet = preparedStatement.executeQuery();
        List<User> users = new ArrayList<>();
        while (resultSet.next()){
            int id = resultSet.getInt("id");
            String username = resultSet.getString("username");
            String userPassword = resultSet.getString("password");
            int age = resultSet.getInt("age");
            User getUser = new User(id,username,userPassword,age);
            users.add(getUser);
        }

        users.forEach(System.out::println);

        preparedStatement.close();
        connection.close();
    }
}
